import routes from "~pages";
import useUserStore from "@/store/modules/useUserStore";
import { treeFind, filterTree, mapTree } from "@/utils/tree";

//获取路由菜单项
function getRouteMenus(scope = "") {
  const userStore = useUserStore();
  const roles = userStore.roles;
  const menus = scope
    ? treeFind(routes, item => {
        if (item.name == scope) return true;
      })?.children
    : routes;
  const fMenus = filterTree(menus ?? [], item => {
    if (scope && !item.name.includes(scope)) {
      return false;
    }
    if (!item.meta.menu) {
      return false;
    }
    if (item.meta.roles) {
      const hasRole = roles.some(r => item.meta.roles?.includes(r));
      if (!hasRole) {
        return false;
      }
    }
    return true;
  });
  const mMenu = mapTree(fMenus ?? [], item => {
    return {
      icon: item.meta.icon,
      title: item.meta.title,
      path: item.path
    };
  });
  return mMenu;
}

export { getRouteMenus };
